// 引入路由
import { createRouter, createWebHistory } from 'vue-router'
import store from './store'
import axios from 'axios'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import Signup from './views/Signup.vue'
import ColumnDetail from './views/ColumnDetail.vue'
import CreatePost from './views/CreatePost.vue'
import PostDetail from './views/PostDetail.vue'
const routerHistory = createWebHistory()
// 创建路由器
const router = createRouter({
    history: routerHistory,
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/login',
            name: 'login',
            component: Login,
            // 已经登陆之后访问login界面时会跳转到首页而不是login界面
            meta: { redirectAlreadyLogin: true }
        },
        {
            path: '/signup',
            name: 'signup',
            component: Signup,
            meta: { redirectAlreadyLogin: true }
        },
        {
            path: '/column/:id',
            name: 'column',
            component: ColumnDetail
        },
        {
            path: '/create',
            name: 'create',
            component: CreatePost,
            meta: { requiredLogin: true }
        },
        {
            path: '/posts/:id',
            name: 'post',
            component: PostDetail
        }
    ]
})
// 创建路由全局前置守卫
router.beforeEach((to, from, next) => {
    const { user, token } = store.state
    const { redirectAlreadyLogin, requiredLogin } = to.meta
    if (!user.isLogin) {
        if (token) {
            axios.defaults.headers.common.Authorization = `Bearer ${token}`
            store.dispatch('fetchCurrentUser').then(() => {
                if (redirectAlreadyLogin) {
                    next('/')
                } else {
                    next()
                }
            }).catch(() => {
                store.state.token = ''
                localStorage.removeItem('token')
                next('login')
            })
        } else {
            if (requiredLogin) {
                next('login')
            } else {
                next()
            }
        }
    } else {
        if (redirectAlreadyLogin) {
            next('/')
        } else {
            next()
        }
    }
})
export default router
